var _util = require('util/util.js');
const { getServerURL, request } = require('../util/util');

var _cart_service = {
    getCart: function (resolve, reject) {
        // 获取当前登录用户名和token
        const username = localStorage.getItem('username');
        const token = localStorage.getItem('token');
         // 检查登录状态
         if (!username || !token) {
            reject('请先登录');
            _util.doLogin();
            return;
        }
        _util.request({
            url: _util.getServerURL('cart/'+username),
            method: "GET",
            headers: {
                'Authorization': 'Bearer ' + token
            },
            contentType: "application/json", // 设置 Content-Type 为 JSON
            success: function(res) {
                if (res.status === 0) {
                    // 计算购物车总价
                    const total = res.data.reduce((sum, item) => sum + item.itemtotal, 0);
                    
                    // 格式化数据以匹配模板
                    const formattedData = {
                        cartList: res.data.map(item => ({
                            itemId: item.itemid,
                            productId: item.productid, 
                            quantity: item.quantity,
                            listPrice: item.unitprice.toFixed(2),
                            total: item.itemtotal.toFixed(2),
                            inStock: item.status === "OK" ? "Yes" : "No",
                            description: item.attr1
                        })),
                        subTotal: total.toFixed(2)
                    };
                    resolve(formattedData);
                } else {
                    reject(res.msg || '获取购物车失败');
                }
            },
            error: function(err) {
                if (err.status === 401) {
                    _util.doLogin();
                } else {
                    reject(err.responseJSON?.msg || '请求失败');
                }
            }
        })
    },

    //对应后端insertItem接口  items/{itemId}
    // insertItem: function (workingItemId, resolve, reject) {
    //     _util.request({
    //         url: _util.getServerURL('cart/items/' + workingItemId),
    //         data: { workingItemId },
    //         method: "GET",
    //         headers: {
    //             Authorization: 'Bearer ' + localStorage.getItem('token') // 假设 token 存储在 localStorage 中
    //         },
    //         success: resolve,
    //         error: reject,
    //     })
    // },
    insertItem: function(itemId) {
        console.log('正在添加商品到购物车:', itemId);
        console.log('当前 token:', localStorage.getItem('token'));
        
        // 检查登录状态
        if (!localStorage.getItem('token')) {
            _util.doLogin();// 跳转登录
            return;
        }
        
        // 继续购物车操作
        _util.request({
            url: _util.getServerURL('cart/items/' + itemId),
            data: JSON.stringify({
                workingItemId: itemId
            }),
            method: 'POST',
            contentType: 'application/json',
            headers: {  // 添加请求头
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            },
            success: function(res) {
                if (res.status === 0||res.status===200) {
                    // 成功添加到购物车
                    alert('成功添加到购物车！');
                } else {
                    alert(res.msg || '添加购物车失败');
                }
            },
            error: function(err) {
                console.error('添加购物车错误:', err);
                if(err.status === 401) {
                    // _util.doLogin();
                } else {
                    alert('添加购物车失败: ' + (err.responseJSON?.msg || '未知错误'));
                }
            }
        });
    },
    
    removeItem: function (itemId, resolve, reject) {
        _util.request({
            url: _util.getServerURL('cart/items/'+itemId),
            data: { itemId },
            method: "DELETE",
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            },
            contentType: "application/json",
            success: resolve,
            error: reject,
        })
    },

    updateItem: function (id, quantity, resolve, reject) {
        _util.request({
            url: _util.getServerURL('cart/items/' + id),
            data: quantity,  // 直接发送数值
            method: "PUT",
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            },      
            contentType: "application/json",
            success: resolve,
            error: reject,
        })
    },

}

module.exports = _cart_service;